﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using QzgfFrame.Utility.Core.Export;

namespace QzgfFrame.Utility.Core.Common
{
    /// <summary>
    /// 提供将泛型集合数据导出Excel文档。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ExcelResult<T> : ActionResult where T : new()
    {
        public ExcelResult(IList<T> entity, string fileName,string id)
        {
            this.Entity = entity;
            this.FileName = fileName;
            this.Id = id;
        }

        public ExcelResult(IList<T> entity)
        {
            this.Entity = entity;

            DateTime time = DateTime.Now;
            this.FileName = string.Format("{0}_{1}_{2}_{3}",
                time.Month, time.Day, time.Hour, time.Minute);

            this.Id = "id";
        }

        public IList<T> Entity
        {
            get;
            set;
        }

        public string FileName
        {
            get;
            set;
        }

        public string Id
        {
            get;
            set;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (Entity == null)
            {
                new EmptyResult().ExecuteResult(context);
                return;
            }

            SetResponse(context);
        }

        /// <summary>
        /// 设置并向客户端发送请求响应。
        /// </summary>
        /// <param name="context"></param>
        private void SetResponse(ControllerContext context)
        {
            var ex = new ExportUtil<T>();
            Hashtable list = ex.ExportConfig("~/Config/exports.xml");
            var exportInfo = list[this.Id] as ExportInfo;
            var bytestr = new byte[] { };
            ex.Exportlist = this.Entity;
            if (exportInfo != null)
                ex.Export(out bytestr, "xls", exportInfo.GetFileName(), exportInfo.GetFields(), exportInfo.GetColumns());
          
            context.HttpContext.Response.Clear();
            context.HttpContext.Response.ClearContent();
            context.HttpContext.Response.Buffer = true;
            //context.HttpContext.Response.Charset = "GB2312";
            //context.HttpContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
            context.HttpContext.Response.ContentType = "application/vnd.ms-excel";//application/ms-excel
            context.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName) + ".xls");
            context.HttpContext.Response.AddHeader("Content-Length", bytestr.Length.ToString());
            context.HttpContext.Response.BinaryWrite(bytestr);
            context.HttpContext.Response.End();
        }

    }
}
